/*
 * Copyright 2009 Red Hat, Inc.
 *
 * Red Hat licenses this file to you under the Apache License, version 2.0
 * (the "License"); you may not use this file except in compliance with the
 * License.  You may obtain a copy of the License at:
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.jd.nettydemo.client;

import com.jd.nettydemo.codec.KryoDecoder;
import com.jd.nettydemo.codec.KryoEncoder;
import com.jd.nettydemo.domain.RequestMessage;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.log4j.Logger;

public class KryoCodecClient {
    /**
     * logger
     */
    private static final Logger logger = Logger.getLogger(KryoCodecClient.class);
    public static String HOST = "127.0.0.1";
    public static int PORT = 8080;

    public static void main(String[] args) throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap(); // (1)
            b.group(workerGroup); // (2)
            b.channel(NioSocketChannel.class); // (3)
            b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    RequestMessage msg = new RequestMessage();
                    msg.setAppId("ssfTestAppID@client");
                    msg.setServiceName("hello@client");
                    msg.setRequestTime(System.currentTimeMillis());
                    ch.pipeline().addLast(new KryoDecoder(), new KryoEncoder(), new KryoCodecClientHandler(msg));
                }
            });

            // 启动客户端
            ChannelFuture f = b.connect(HOST, PORT).sync(); // (5)

            // 等待连接关闭
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
